package com.conversationboard.batch.jobs.stats;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.conversationboard.database.BatchQueries;
import com.conversationboard.database.Database;
import com.conversationboard.site.Site;

public class CountersJob implements Job {

	public void initialiseCounters() throws JobExecutionException {

		Connection connection = null;

		try {

			System.out.println("---------- Executing COUNTERS JOB -------");
			
			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(BatchQueries.COUNT_ALL_MESSAGES);
			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {
				Site.setMessageCount(resultSet.getLong("total"));
			}

			statement = connection.prepareStatement(BatchQueries.COUNT_ALL_THREADS);
			statement.execute();

			resultSet = statement.getResultSet();

			while (resultSet.next()) {
				Site.setThreadCount(resultSet.getLong("total"));
			}

			statement = connection.prepareStatement(BatchQueries.COUNT_ALL_USERS);
			statement.execute();

			resultSet = statement.getResultSet();

			while (resultSet.next()) {
				Site.setUserCount(resultSet.getLong("total"));
			}

		} catch (SQLException e) {
			throw new JobExecutionException(e);
		} finally {
			try {
				Database.close(connection);
			} catch (SQLException e) {
				throw new JobExecutionException(e);
			}
		}
	}


	public void execute(JobExecutionContext context) throws JobExecutionException {
		this.initialiseCounters();
	}
	
}
